package com.greate.community.quartz;

import com.greate.community.entity.DiscussPost;
import com.greate.community.service.DiscussPostService;
import com.greate.community.service.ExpService;
import com.greate.community.constant.CommunityConstant;
import com.greate.community.constant.ExpType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

@Slf4j
@Component
public class SchedulerTask implements CommunityConstant {

    static int LIKE_COUNT_TO_EXP = 10;

    @Autowired
    private DiscussPostService discussPostService;

    @Autowired
    private ExpService expService;

    /**
     * 帖子获赞转经验定时任务，每日4点定时执行
     */
    @Scheduled(cron = "0 0 4 * * ?")
    private void executePostLikeToExp() {
        log.info("[start post like to exp task]");
        Calendar calendar = Calendar.getInstance();
        // 获取7天前的日期
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - 7);
        String startDate = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
        // 加1天，得到6天前的日期
        calendar.add(Calendar.DATE, 1);
        String endDate = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());

        List<DiscussPost> discussPostList = discussPostService.findDiscussPosts(0, 0, Integer.MAX_VALUE, 0, startDate, endDate, 10);

        // 将点赞数按照帖子点赞量进行转化
        discussPostList.forEach(discussPost -> {
            int expCount = discussPost.getLikeCount() / ExpType.EXP_POST_LIKE_COUNT.getCount();
            expService.addExp(discussPost.getUserId(), expCount, ExpType.EXP_POST_LIKE_COUNT.getName());
        });
    }
}